//
//  BaiduMapVC.m
//  honglaba
//
//  Created by 红喇叭 on 2017/6/28.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "BaiduMapVC.h"
#import <MapKit/MapKit.h>
#import "objc/runtime.h"
#import "BMKPoiSearchType.h"

static const void * OrderTagsBy = &OrderTagsBy;

@implementation BMKPointAnnotation (addTag)

- (void)setTag:(NSString *)tag{
    objc_setAssociatedObject(self, OrderTagsBy, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (NSString *)tag{
    return objc_getAssociatedObject(self, OrderTagsBy);
}

@end

@interface BaiduMapVC ()<BMKGeoCodeSearchDelegate>{
    CLLocationCoordinate2D coor;//目的地
    BMKPointAnnotation* _annotation;
}
@property (nonatomic, strong) BMKGeoCodeSearch *geocodesearch;
@end

@implementation BaiduMapVC

- (void)dealloc{
    
}

- (void)viewDidLoad {    
    [super viewDidLoad];
    
   
    self.view.backgroundColor = [UIColor whiteColor];
    _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W,SCREEN_H-100)];
    _mapView.mapType = BMKMapTypeStandard;
    _mapView.showsUserLocation = YES;
    [_mapView setZoomLevel:19.0];
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
    
    
    
    UIButton *updateLocation = [[UIButton alloc] init];
    [updateLocation setBackgroundImage:[UIImage imageNamed:@"dt_shuax.png"] forState:UIControlStateNormal];
    [updateLocation addTarget:self action:@selector(location) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:updateLocation];
    updateLocation.sd_layout.leftSpaceToView(_mapView,20).bottomSpaceToView(_mapView, 20).widthIs(40).heightIs(40);

   

//    _annotation = [[BMKPointAnnotation alloc]init];
//    
//    [_mapView addAnnotation:_annotation];

    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    
    _geocodesearch.delegate = self;
    
    NSDictionary *dic = [userDefaults objectForKey:@"agentInfo"];
    
    coor.latitude = (CLLocationDegrees)[dic[@"latitude"] doubleValue];
    coor.longitude = (CLLocationDegrees)[dic[@"longitude"] doubleValue];
//    _annotation.coordinate = coor;
//    [_mapView removeOverlays:_mapView.overlays];
    [_mapView setCenterCoordinate:coor animated:true];
    [self bottomView:dic[@"address"] name:dic[@"agent_name"]];
  //  [self refreshLocation];
    
    UIImage *coordinatesImg = [UIImage imageNamed:@"dt_mdd.png"];
    UIImageView *center = [[UIImageView alloc] initWithImage:coordinatesImg];
    center.frame = CGRectMake(0, 0, coordinatesImg.size.width*(3/4.0), coordinatesImg.size.height*(3/4.0));
    center.center = _mapView.center;
    [self.view addSubview:center];
    
    __weak typeof(self) weakself=self;
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10,22, 44, 44);
    [backBtn setImage:[UIImage imageNamed:@"dh_back.png"] forState:UIControlStateNormal];
    [backBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakself.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.view addSubview:backBtn];
    
    [self NetworkStatus];
}


#pragma mark -- 实时监测网络状态的变化
- (void)NetworkStatus {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"打开WIFI定位更精准" delegate:nil cancelButtonTitle:@"确定"otherButtonTitles:nil, nil];
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /*
         status
         AFNetworkReachabilityStatusUnknown          = -1, 不知道监测的是什么
         AFNetworkReachabilityStatusNotReachable     = 0,  没有检测到网络
         AFNetworkReachabilityStatusReachableViaWWAN = 1,  蜂窝网
         AFNetworkReachabilityStatusReachableViaWiFi = 2,  WIFI
         */
        
        if(status != AFNetworkReachabilityStatusReachableViaWiFi){
             [alert show];
        }
    }];
    // 开始监测
    [manager startMonitoring];
}



- (void)updateAdress{
    __weak typeof(self)weakself = self;
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请确认是否修改店铺坐标为当前定位坐标?" preferredStyle:UIAlertControllerStyleAlert];
    [alter addAction:[UIAlertAction actionWithTitle:@"我再想想" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [alter addAction:[UIAlertAction actionWithTitle:@"确认修改" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself updateShopInfo];
    }]];
    
    [self presentViewController:alter animated:YES completion:nil];
}


- (void)updateShopInfo{
    NSDictionary *dic = [userDefaults objectForKey:@"agentInfo"];
    
    __weak typeof(self)weakself = self;
    NSDictionary *pramar = @{@"latitude":[NSString stringWithFormat:@"%f",coor.latitude],
                             @"longitude":[NSString stringWithFormat:@"%f",coor.longitude]
                             };
    
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/ShopInfo/changeInfo" parameter:pramar successBlock:^(PPHttpRequest *request, id responseObj) {
        NSMutableDictionary *newInfo = dic.mutableCopy;
        [newInfo setObject:responseObj[@"latitude"] forKey:@"latitude"];
        [newInfo setObject:responseObj[@"longitude"] forKey:@"longitude"];
        [userDefaults setObject:newInfo forKey:@"agentInfo"];
        [weakself.navigationController popViewControllerAnimated:YES];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}


- (void)viewWillAppear:(BOOL)animated{
    if(_geocodesearch == nil){
        _geocodesearch = [[BMKGeoCodeSearch alloc] init];
        _geocodesearch.delegate = self;
    }
    _mapView.delegate = self;
    
    if(_locationManager==nil){
        _locationManager = [[BaiduLoaction alloc] init];
    }
 [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    _geocodesearch.delegate = nil;
    _geocodesearch = nil;
    _locationManager = nil;
   [self.navigationController setNavigationBarHidden:NO];
}

#pragma mark --定位功能

-(void)location
{
  //  [_mapView removeAnnotations:_mapView.annotations];
    [AlertUtils showHudInView:self.view hint:@"正在获取当前位置"];
    
    if(_locationManager==nil){
        _locationManager = [[BaiduLoaction alloc] init];
    }
    __weak typeof(self) weakself=self;
    [_locationManager Start:^(BMKReverseGeoCodeResult *result) {
        NSLog(@"%@",result);
        [AlertUtils hideHud];
        if(result==nil){
            [weakself.navigationController popViewControllerAnimated:YES];
            [AlertUtils showHudInView:self.view hint:@"获取位置信息失败" hideAfterDelay:2];
            
        }else{
            
            BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
            annotation.coordinate = result.location;
            annotation.title = result.address;
            _annotation.title = result.address;
            _annotation.coordinate = result.location;
            annotation.tag =@"start";
          //  BMKPoiInfo *info = result.poiList.firstObject;
            [weakself bottomView:result.address name:result.sematicDescription];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_mapView removeOverlays:_mapView.overlays];
                [_mapView setCenterCoordinate:result.location animated:true];
                [_mapView addAnnotation:_annotation];
                
            });
                        
        }
        
    } loctionFail:^(NSString *ErrCode) {
        
        [weakself.navigationController popViewControllerAnimated:YES];
        [AlertUtils showHudInView:self.view hint:@"获取位置信息失败" hideAfterDelay:2];

    }];
}


- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    MKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
    _annotation.coordinate = centerCoordinate;
    coor = centerCoordinate;
    [self refreshLocation];

   // NSLog(@" regionDidChangeAnimated %f,%f",centerCoordinate.latitude, centerCoordinate.longitude);
}

- (void)refreshLocation{
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    reverseGeocodeSearchOption.reverseGeoPoint = coor;
    
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    
    if(flag){
        
        NSLog(@"反geo检索发送成功");
        
    }else{
        NSLog(@"反geo检索发送失败");
        
    }

}

//反编码失败
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    [AlertUtils showHudInView:self.view hint:@"反检索失败,您可要点击右下角的刷新尝试获取！"];
}

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    BMKPoiInfo *info = result.poiList.firstObject;
    _annotation.title = result.address;
      [self bottomView:result.address name:info.name];
}
- (void)bottomView:(NSString*)dantense name:(NSString *)adrname{
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H-100, SCREEN_W, 100)];
    
    UILabel *name = [[UILabel alloc] init];
    name.font = [UIFont fontWithName:@"STKaiti" size:20];
    name.text = adrname;
    [bottomView addSubview:name];
    name.sd_layout.leftSpaceToView(bottomView, 15).topSpaceToView(bottomView, 15).heightIs(20).widthIs(0);
    [name setSingleLineAutoResizeWithMaxWidth:(300)];
    NSString *str = @"";

     str = [NSString stringWithFormat:@"%@",dantense];

    UILabel *address = [[UILabel alloc] init];
    address.font = [UIFont systemFontOfSize:14];
    address.textColor = [UIColor grayColor];
    address.text = str;
    [bottomView addSubview:address];
    address.sd_layout.leftEqualToView(name).topSpaceToView(name, 10).rightSpaceToView(bottomView, 80).autoHeightRatio(0).maxHeightIs(50);
    
    
    UIImageView *daoIMG = [[UIImageView alloc] init];
    [bottomView addSubview:daoIMG];
    daoIMG.image = [UIImage imageNamed:@"mipmap-xxxhdpi.png"];
    daoIMG.sd_layout.rightSpaceToView(bottomView, 60).widthIs(15).heightIs(20).centerYEqualToView(bottomView);
    UILabel *daohang = [[UILabel alloc] init];
    daohang.text = @"修改";
    daohang.textColor = [UIColor redColor];
    daohang.font = [UIFont fontWithName:@"STKaiti" size:30];
    daohang.backgroundColor = [UIColor clearColor];
    [bottomView addSubview:daohang];
    daohang.sd_layout.leftSpaceToView(daoIMG,2).widthIs(0).heightIs(30).centerYEqualToView(bottomView);
    [daohang setSingleLineAutoResizeWithMaxWidth:(100)];

    
    UIButton *button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(updateAdress) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:button];
    button.sd_layout.rightSpaceToView(bottomView, 60).rightSpaceToView(bottomView, 0).heightIs(40).centerYEqualToView(bottomView);
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
}

/// 百度坐标转高德坐标
- (CLLocationCoordinate2D)GCJ02FromBD09:(CLLocationCoordinate2D)coors
{
    CLLocationDegrees x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    CLLocationDegrees x = coors.longitude - 0.0065, y = coors.latitude - 0.006;
    CLLocationDegrees z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
    CLLocationDegrees theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
    CLLocationDegrees gg_lon = z * cos(theta);
    CLLocationDegrees gg_lat = z * sin(theta);
    return CLLocationCoordinate2DMake(gg_lat, gg_lon);
}

//根据宽度计算高度
- (CGFloat)calculateRowHeight:(NSString *)string fontSize:(UIFont *)font with:(CGFloat)with{
    NSDictionary *dic = @{NSFontAttributeName:font};//指定字号
    CGRect rect = [string boundingRectWithSize:CGSizeMake(with, 0)/*计算高度要先指定宽度*/ options:NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.height;
}

@end
